<?php
function add_new_teacher_msg($conn,$title,$content,$fors,$tos){
    $time = date('Y-m-d H:i:s');
    $query = "insert into exam_msg(title,content,fors,tos,time) values (?,?,?,?,?)";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("sssss", $title, $content, $fors, $tos, $time); 
    if($stmt->execute()){
        return true;
    } else {
        return false;
    }
}
$bid = $_POST['bid'];
$forwho = $_POST['forid'];
$name = $_POST['name'];
if($bid == ''){
    echo "<script>alert('参数异常');location='../bind.php?mno=bd';</script>"; 
    exit;
}
require('../../../cofd/common.php');
require('../../../cofd/functions.php');
$jm_my = encrypt($bid,'D','teache_byhbindkey721');
$queryCheck = "SELECT * FROM exam_user WHERE id = ?";
$stmtCheck = $conn->prepare($queryCheck);
$stmtCheck->bind_param("s", $jm_my);
$stmtCheck->execute();
$resultCheck = $stmtCheck->get_result();
if ($resultCheck->num_rows > 0) {
    $queryGetBindTeacher = "SELECT bindteacher FROM exam_student WHERE id = ?";
    $stmtGetBindTeacher = $conn->prepare($queryGetBindTeacher);
    $stmtGetBindTeacher->bind_param("s", $forwho);
    $stmtGetBindTeacher->execute();
    $resultGetBindTeacher = $stmtGetBindTeacher->get_result();
    if ($resultGetBindTeacher->num_rows > 0) {
        $row = $resultGetBindTeacher->fetch_assoc();
        $currentBindTeacher = $row['bindteacher'];
    }
    $queryUpdate = "UPDATE exam_student SET bindteacher = ? WHERE id = ?";
    $stmtUpdate = $conn->prepare($queryUpdate);
    $newplus = $currentBindTeacher.$jm_my.',';
    $stmtUpdate->bind_param("ss", $newplus, $forwho);
    if($stmtUpdate->execute()){
        $title_c = '学生'. $name . '已绑定你';
        $newcontent_c = '学生'. $name . '已绑定你';
        if(add_new_teacher_msg($conn,$title_c,$newcontent_c,$jm_my,'t')){
            echo "<script>alert('绑定成功');location='../bind.php?mno=bd';</script>";
        } else {
            echo "<script>alert('绑定失败');location='../bind.php?mno=bd';</script>"; 
        }
    } else {
        echo "<script>alert('绑定失败');location='../bind.php?mno=bd';</script>"; 
    }
} else {
    echo "<script>alert('绑定失败-ID码不存在');location='../bind.php?mno=bd';</script>"; 
}
$resultCheck->close();
$resultGetBindTeacher->close();
$stmtCheck->close();
$stmtUpdate->close();
$conn->close();
